package com.disk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.disk.config.AppConfig;
import com.disk.entity.po.EmailCode;
import com.disk.entity.po.UserInfo;
import com.disk.exception.BusinessException;
import com.disk.mapper.EmailCodeMapper;
import com.disk.mapper.UserInfoMapper;
import com.disk.service.EmailCodeService;
import com.disk.utils.StringTools;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 邮箱验证码 服务实现类
 * </p>
 *
 * @author zsy
 * @since 2024-08-06
 */
@Service
public class EmailCodeServiceImpl extends ServiceImpl<EmailCodeMapper, EmailCode> implements EmailCodeService {

    @Resource
    private EmailCodeMapper emailCodeMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private AppConfig appConfig;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendEmailCode(String email, Integer type) {
        if (type == 0) {
            UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getEmail, email));
            if (userInfo != null) {
                throw new BusinessException("邮箱已被注册");
            }
        }
        String code = StringTools.getRandomNumber(5);
        sendCode(email, code);
        //删除该邮箱之前的验证码
        emailCodeMapper.delete(new LambdaQueryWrapper<EmailCode>().eq(EmailCode::getEmail, email));

        EmailCode emailCode = new EmailCode();
        emailCode.setCode(code);
        emailCode.setEmail(email);
        emailCode.setStatus(0);//0-未使用，1-已使用
        emailCode.setCreateTime(LocalDateTime.now());
        emailCodeMapper.insert(emailCode);
    }

    @Override
    public void checkCode(String email, String code) {
        EmailCode emailCode = emailCodeMapper.selectOne(new LambdaQueryWrapper<EmailCode>().eq(EmailCode::getEmail, email));
        if (emailCode == null) {
            throw new BusinessException("验证码不存在");
        }
        if (emailCode.getCreateTime().plusMinutes(15).isBefore(LocalDateTime.now())) {
            throw new BusinessException("验证码已过期");
        }
        if (emailCode.getStatus() == 1) {
            throw new BusinessException("验证码已使用");
        }
        if (!code.equals(emailCode.getCode())) {
            throw new BusinessException("验证码错误");
        }
        emailCode.setStatus(1);
        emailCodeMapper.updateById(emailCode);

    }

    private void sendCode(String toEmail, String code) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(appConfig.getAdminEmails());
            helper.setTo(toEmail);
            helper.setSubject("MyDisk验证码");
            helper.setText("您的验证码为：" + code + "，有效期15分钟，请勿泄露。");
            helper.setSentDate(new Date());
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("发送邮件失败", e);
            throw new BusinessException("发送邮件失败");
        }
    }
}
